<template>
  <div>
    <v-menu offset-y open-on-hover transition="scroll-y-transition">
      <template v-slot:activator="{ on, attrs }">
        <v-btn text v-bind="attrs" v-on="on">
          <svg-icon class="internationalIconClass" :icon-class="internationalIcon"></svg-icon>
        </v-btn>
      </template>

      <v-list dense class="pa-0">
        <v-list-item-group v-model="selectedILang">
          <v-list-item v-for="(item, i) in items" :key="i" dense @click="selectLang">
            <v-btn class="justify-start" :color="scssVariables.appBarMenuColor" text block left>
              {{ item.text }}
            </v-btn>
          </v-list-item>
        </v-list-item-group>
      </v-list>
    </v-menu>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import scssVariables from '@/styles/variables.scss'

export default {
  // 切换国际化
  name: 'LangSelect',

  data() {
    return {
      internationalIcon: '',
      selectedILang: undefined,
      items: [
        { text: 'English', value: 'en' },
        { text: '中文', value: 'zhHans' }
      ],
      scssVariables
    }
  },

  computed: {
    ...mapGetters(['lang'])
  },

  watch: {
    lang(nv) {
      this.items.forEach((item, i) => item.value === nv && (this.selectedILang = i))
      // console.log(this.$refs.langSelect)
      this.redirectPath()
    },

    selectedILang(nv) {
      this.$store.dispatch('i18n/setI18nLang', this.items[nv].value)
    }
  },

  created() {
    this.internationalIcon = this.lang === 'zhHans' ? 'CN' : 'EN'
  },

  mounted() {
    this.items.forEach((item, i) => this.lang === item.value && (this.selectedILang = i))
  },

  methods: {
    selectLang(event, key) {
      // console.log(event, key)
    },

    redirectPath() {
      this.$nextTick(() => {
        this.$router.replace({
          path: '/redirect' + this.$route.path
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.internationalIconClass {
  width: 2em !important;
  height: 2em !important;
}
</style>
